package crowx.android.AndCellTrack;

import java.io.InputStream;
import java.util.List;

import com.google.android.maps.MapView;
import com.google.android.maps.MyLocationOverlay;
import com.google.android.maps.Overlay;

import crowx.android.AndCellTrack.BtsDB.BtsDB;
import crowx.android.AndCellTrack.BtsDB.BtsInfo;

import android.content.Context;
import android.location.Location;
import android.location.LocationManager;
import android.os.Bundle;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.LinearLayout.LayoutParams;

public class AndCellTrack extends AndCellTrackBase {
	private TextView cellInfoView = null;
	private LocationManager locationManager = null;
	private MyLocationOverlay myLocationOverlay = null;
	private BtsDB btsDB = null;
	private List<Overlay> mapOverlays;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        cellInfoView = (TextView)findViewById(R.id.CellInfoL0);
        MapView mapView = (MapView)this.findViewById(R.id.MapView);
        
        LinearLayout zoomLayout = (LinearLayout)findViewById(R.id.zoom);  
        View zoomView = mapView.getZoomControls(); 
 
        zoomLayout.addView(zoomView,
            new LinearLayout.LayoutParams(
                LayoutParams.WRAP_CONTENT, 
                LayoutParams.WRAP_CONTENT)); 
        mapView.displayZoomControls(true);
        
        myLocationOverlay = new MyLocationOverlay(this.getApplicationContext(),mapView);
        myLocationOverlay.enableCompass();
        myLocationOverlay.enableMyLocation();
        
        mapOverlays = mapView.getOverlays();
        mapOverlays.clear();        
        mapOverlays.add(myLocationOverlay);
        mapOverlays.add(new BtsOverlay(50.078889,22.225556));
        
        //if(preferences.getBoolean("use_gps",true)) {
			locationManager = (LocationManager)getSystemService(Context.LOCATION_SERVICE);
			//locationManager.requestLocationUpdates(LocationManager.GPS_PROVIDER, 500, 0, locationListener);
		//}
        
        btsDB = new BtsDB();
        InputStream is = getResources().openRawResource(R.raw.btspod);
        btsDB.loadFromCLFFile(is);
    }

	@Override
	protected boolean isRouteDisplayed() {
		return false;
	}

	@Override
	protected void onStateChanged(CellInfo cellInfo) {
		cellInfoView.setText(cellInfo.toString());
		
		mapOverlays.clear();        
        mapOverlays.add(myLocationOverlay);
		
        Location loc = locationManager.getLastKnownLocation(LocationManager.GPS_PROVIDER);
        if(loc != null) {
	        List<BtsInfo> lb = btsDB.getNearest(new double[]{loc.getLatitude(),loc.getLongitude()}, 15);
			for(BtsInfo b: lb) {
				mapOverlays.add(new BtsOverlay(b.getKey()));
			}
        }
	}
    
}